package com.lazy.utils.utils;


import com.lazy.utils.exception.ProgramException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化对象工具
 *
 * @author zk
 * @since 2018-04-23 15:26
 */
public class SerializeUtil {

	/**
	 * 序列化对象为字符串
	 */
	public static String objectSerialization(Object obj) {
		String serStr;
		try {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(obj);
			serStr = byteArrayOutputStream.toString("ISO-8859-1");
			serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
			objectOutputStream.close();
			byteArrayOutputStream.close();
		} catch (Exception e) {
			throw new ProgramException(e);
		}
		return serStr;
	}

	/**
	 * 字符串反序列化为对象
	 */
	public static Object objectDeserialization(String serStr) {
		Object newObj;
		try {
			String redStr = java.net.URLDecoder.decode(serStr, "UTF-8");
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
			ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
			newObj = objectInputStream.readObject();
			objectInputStream.close();
			byteArrayInputStream.close();
		} catch (Exception e) {
			throw new ProgramException(e);
		}
		return newObj;
	}

}
